
<template>
  <div class="add_question">
    <div class="question_title">{{ id ? '编辑' : '新增'}}知识点</div>
    <el-form ref="formRef" :model="form" :rules="rules">
      <el-form-item label="问题内容" prop="content">
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="4"
          maxlength="255"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="问题选项" prop="option">
        <div class="option_list">
          <div
            v-for="(item, index) in form.option"
            :key="`option${index}`"
            :style="{
              'left': 0,
              'top': (item.code.charCodeAt() - 97) * 35 + 'px'
            }"
            class="option_item"
          >
            <div class="code">
              <el-select v-model="item.code" :disabled="index < 1" style="width: 35px" @change="changeCode(item.code, index)">
                <el-option
                  v-for="item in optionCodeList"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </div>
            <div class="content">
              <el-input v-model="item.content" style="width: 100%"></el-input>
            </div>
            <div class="option_btn" @click="addOption">
              <el-icon><Plus /></el-icon>
            </div>
            <div class="option_btn" @click="deleteOption(index)">
              <el-icon v-show="index > 0"><Delete /></el-icon>
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="问题答案" prop="answer">
        <el-select v-model="form.answer" style="width: 100%">
          <el-option
            v-for="item in optionCodeList"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="答案解释" prop="explain">
        <el-input
          v-model="form.explain"
          type="textarea"
          :rows="4"
          maxlength="255"
          show-word-limit
        ></el-input>
      </el-form-item>
    </el-form>
    <div class="operation">
      <div class="cancel_btn" @click="cancel">取消</div>
      <div class="submit_btn" @click="submit">提交</div>
    </div>
  </div>
</template>
<script setup>
import {
  addQuestion,
  updateQuestionById,
  getQuestionById,
  addAccount,
  updateAccountById,
  addElement,
  updateElementById,
  addIngredient,
  updateIngredientById
} from '@/views/settings/backend/api'
import { ref, reactive, defineProps, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { Plus, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const optionCodeList = reactive(['a', 'b', 'c', 'd', 'e', 'f'])
let copyOptionList = reactive([])
const initForm = reactive({
  content: '',
  option: [{ code: 'a', content: '我是a' }, { code: 'b', content: '我是b' }],
  answer: 'a',
  explain: '暂无',
  remark: ''
})
const form = ref({ ...initForm })

const formRef = ref(null)

const rules = reactive({
  content: [
    {
      required: true,
      message: '请输入问题内容',
      trigger: 'blur'
    }
  ],
  option: [
    {
      required: true,
      message: '请输入问题选项',
      trigger: 'blur'
    }
  ],
  answer: [
    {
      required: true,
      message: '请输入问题答案',
      trigger: 'blur'
    }
  ]
})
let id = reactive('')

onMounted(() => {
  const route = useRoute()
  id = route.query.id
  copyOptionList = JSON.parse(JSON.stringify(form.value.option))
  if (id) {
    getQuestionById(id).then((res) => {
      const result = res.result
      if (result.option) {
        const option = JSON.parse(result.option)
        const list = []
        for (const key in option) {
          list.push({
            code: key,
            content: option[key]
          })
        }
        result.option = list
      }
      form.value = result
    })
  }
})

const changeCode = (code, index) => {
  const originList = form.value.option
  const originIndex = copyOptionList.findIndex(item => item.code === code)
  // console.log(originIndex, '===========>', copyOptionList)
  if (originIndex >= 0) {
    // 两者互换
    const currentCode = copyOptionList[index].code
    originList[index].code = copyOptionList[originIndex].code
    originList[originIndex].code = currentCode
  }

  copyOptionList = JSON.parse(JSON.stringify(originList))
}

const addOption = () => {
  // 求得空缺的最小的字符
  const currentCodeList = form.value.option.map(item => item.code)
  const freeCode = optionCodeList.filter(item => !currentCodeList.includes(item))
  const maxCharCode = Math.min(...freeCode.map(item => item.charCodeAt()))
  if (freeCode.length === 0 || maxCharCode > 102) {
    ElMessage({
      type: 'error',
      message: '最多只能添加6个选项'
    })
    return
  }
  form.value.option.push({
    code: String.fromCharCode(maxCharCode),
    content: ''
  })

  copyOptionList = JSON.parse(JSON.stringify(form.value.option))
}
const deleteOption = (index) => {
  if (index === 0) return
  form.value.option.splice(index, 1)
  copyOptionList = JSON.parse(JSON.stringify(form.value.option))
}
  

const resetFields = (formData) => {
  const data = formData || initForm
  form.value = { ...data }
  copyOptionList = JSON.parse(JSON.stringify(form.value.option))
  formRef.value.clearValidate()
}

const submit = () => {
  return new Promise((resolve, reject) => {
    formRef.value.validate((valid) => {
      if (valid) {
        const optionArr = form.value.option
        const obj = {}
        optionArr.forEach(item => {
          obj[item.code] = item.content
        })
        const params = {
          ...form.value,
          option: JSON.stringify(obj)
        }

        if (id) {
          updateQuestionById(params).then(() => {
            resolve()
            ElMessage({
              type: 'success',
              message: '修改成功'
            })
            cancel()
          })
        } else {
          addQuestion(params).then(() => {
            resetFields()
            ElMessage({
              type: 'success',
              message: '添加成功'
            })
            resolve()
          })
        }
        
        // resolve(params)
      } else {
        // reject(new Error('表单验证不通过'))
      }
    })
  })
}

const cancel = () => {
  history.back()
}

defineExpose({
  resetFields,
  submit
})

</script>
<style lang="scss" scoped>
.add_question {
  padding: 20px;
  width: calc(100% - 50px);

  .question_title {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 50px;
    border-left: 5px solid var(--el-color-primary);
    text-align: left;
    padding-left: 10px;
  }

  ::v-deep .el-form-item__label {
    display: block;
    font-weight: bold;
    text-align: left;
  }

  ::v-deep .el-form-item {
    display: block;
  }

  .option_list {
    position: relative;
    width: 100%;
    height:150px;
    overflow: auto;
    border: 1px solid var(--el-border-color);
    border-radius: 5px;

    .option_item {
      position: absolute;
      display: flex;
      transition: top 0.6s;
      box-sizing: border-box;
      width: 100%;
      height: 35px;
      background-color: #fff;
      border: 1px solid var(--el-border-color);
      border-radius: 5px;
      text-align: left;
      line-height: 35px;
      font-size: 12px;
      font-weight: bold;

      .code {
        width: 40px;
        ::v-deep .el-input__suffix {
          display: none;
        }
        ::v-deep .el-input--suffix {
          transform: translateY(-1px);
          height: 35px;
        }
      }
      .content {
        flex: 1;
        // ::v-deep .el-input__wrapper {
        //   box-shadow: none;
        //   box-sizing: border-box;
        //   transform: translateY(-1px);
        //   border-bottom: 1px solid var(--el-border-color);
        // }
      }
      .option_btn {
        width: 25px;
        text-align: center;
      }
    }
  }

  .operation {
    position: absolute;
    bottom: 80px;
    width: calc(100% - 50px);
    height: 50px;
    display: flex;
    justify-content: end;

    .cancel_btn {
      width: 100px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      border: 1px solid var(--el-color-primary);
      border-radius: 5px;
      margin-right: 20px;
      cursor: pointer;
    }
    .submit_btn {
      width: 100px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      color: #fff;
      background-color: var(--el-color-primary);
      border-radius: 5px;
      cursor: pointer;
    }
  }
}
</style>